package com.itheima;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisMessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    JedisPool jedisPool;
    @Reference
    MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map<String,String>map){
        String telephone = map.get("telephone");
        String validCodeByRedis = jedisPool.getResource().get(RedisMessageConst.SENDTYPE_LOGIN + "-" + telephone);
        String validateCodeByMap = map.get("validateCode");
        if (!(validCodeByRedis!=null&&validCodeByRedis.equals(validateCodeByMap))){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        Member member=memberService.findByTelephone(telephone);
        if (member==null){
            member=new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.addMember(member);
        }
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }
}
